package com.example.studykotlin.kotlin_actual_combat.art.aidl;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.studykotlin.Path;
import com.example.studykotlin.R;
import com.example.studykotlin.databinding.ActivityBookManagerBinding;

import java.util.List;

@Route(path = Path.bookManager)
public class BookManagerActivity extends AppCompatActivity {
    ActivityBookManagerBinding binding;
    private static final String TAG = "BookManagerActivity";

    private static final int MESSAGE_NEW_BOOK_ARRIVED = 1;

    private IBookManager mRemoteBookManager;

    private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            Log.e(TAG, "binder died. tname:" + Thread.currentThread().getName());
            if (mRemoteBookManager != null) return;
            mRemoteBookManager.asBinder().unlinkToDeath(mDeathRecipient,0);
            mRemoteBookManager = null;
            //重新绑定远程Service
            Intent intent = new Intent(BookManagerActivity.this,BookMangerService.class);
            bindService(intent,mConnection, Context.BIND_AUTO_CREATE);
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MESSAGE_NEW_BOOK_ARRIVED:
                    Log.e(TAG, "receive new book:"+ msg.obj );
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mRemoteBookManager = IBookManager.Stub.asInterface(iBinder);
            try {
                iBinder.linkToDeath(mDeathRecipient,0);
                List<Book> list = mRemoteBookManager.getBookList();
                Log.e(TAG, "query book list"+list);
                Book book = new Book(3,"Android开发艺术探索");
                mRemoteBookManager.addBook(book);
                Log.e(TAG, "add Book"+book);
                List<Book> newList = mRemoteBookManager.getBookList();
                Log.e(TAG, "query book list"+newList);
                mRemoteBookManager.registerListener(onNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mRemoteBookManager = null;
            Log.d(TAG, "onServiceDisconnected. tname:" + Thread.currentThread().getName());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBookManagerBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Intent intent = new Intent(this,BookMangerService.class);
        bindService(intent,mConnection, Context.BIND_AUTO_CREATE);

        binding.tvAnr.setOnClickListener(view -> {
            new Thread(() -> {
                if (mRemoteBookManager != null) {
                    try {
                        List<Book> bookList = mRemoteBookManager.getBookList();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        });
    }

    @Override
    protected void onDestroy() {
        if (mRemoteBookManager != null && mRemoteBookManager.asBinder().isBinderAlive()) {
            Log.e(TAG, "unregister listener:"+onNewBookArrivedListener );
            try {
                mRemoteBookManager.unregisterListener(onNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mConnection);
        super.onDestroy();
    }

    private IOnNewBookArrivedListener onNewBookArrivedListener = new IOnNewBookArrivedListener.Stub() {
        @Override
        public void onNewBookArrived(Book book) throws RemoteException {
            mHandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVED,book).sendToTarget();
        }
    };
}